import Cookies from 'js-cookie'
import { getSessionInfo, setSessionInfo, removeSessionInfo } from '@/utils/storage'
import { removeRoutes, setRoutes } from '@/utils/route'
import { PAGE_CODE_LIST } from '@/constants/mock-login-data'

const userInfo = getSessionInfo('userInfo') || {
  id: '',
  account: '',
  department: '',
  departmentId: '',
  name: '',
  avatar: '',
  pwdOverdueTime: '', // 密码过期时间
  needResetPwd: false
}

const menuList = getSessionInfo('menuList') || []
const permissionCodeList = getSessionInfo('permissionCodeList') || []

if (permissionCodeList?.length > 0) {
  setRoutes(permissionCodeList)
}

const state = {
  token: Cookies.get('token'),
  userInfo: userInfo,
  menuList: menuList, // 菜单列表
  permissionCodeList: permissionCodeList.length === 0 ? PAGE_CODE_LIST : permissionCodeList // 所有按钮code的集合
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    Cookies.set('token', token)
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    setSessionInfo('userInfo', userInfo)
  },
  REMOVE_TOKEN (state) {
    state.token = ''
    Cookies.remove('token')
  },
  REMOVE_USER_INFO (state) {
    state.userInfo = {
      id: '',
      account: '',
      department: '',
      departmentId: '',
      name: '',
      avatar: '',
      pwdOverdueTime: '', // 密码过期时间
      needResetPwd: false
    }
    removeSessionInfo('userInfo')
  },
  SET_RESOURCE (state, { menuList, pathList, permissionCodeList }) {
    state.menuList = menuList
    state.pathList = pathList
    state.permissionCodeList = permissionCodeList
    setSessionInfo('menuList', menuList)
    setSessionInfo('pathList', pathList)
    setSessionInfo('permissionCodeList', permissionCodeList)
  },
  REMOVE_RESOURCE (state) {
    removeRoutes(state.permissionCodeList)
    state.menuList = []
    state.pathList = []
    state.permissionCodeList = []
    removeSessionInfo('menuList')
    removeSessionInfo('pathList')
    removeSessionInfo('permissionCodeList')
  }
}

const actions = {
  /**
   * resources： menuList, permissionCodeList, pathList
   * **/
  setLoginData ({ commit }, { userInfo, token, resources = {} }) {
    return new Promise(resolve => {
      commit('SET_USER_INFO', userInfo)
      commit('SET_TOKEN', token)
      commit('SET_RESOURCE', resources)
      setRoutes(resources.permissionCodeList)
      resolve()
    })
  },
  loginOut ({ commit }) {
    return new Promise(resolve => {
      commit('REMOVE_TOKEN')
      commit('REMOVE_USER_INFO')
      commit('REMOVE_RESOURCE')
      resolve()
    })
  }
}

export default {
  state,
  mutations,
  actions
}
